# 从网络上下载一张图片，保存到计算机的指定目录；（requests和os模块）
import requests
from lxml import etree
import datetime
import os


headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'
}


def get_src():
    url = 'https://cn.bing.com/?mkt=zh-CN&mkt=zh-CN'
    resp = requests.get(url, headers=headers)
    page_source = etree.HTML(resp.text)
    href = page_source.xpath('//*[@id="preloadBg"]/@href')[0]
    return href


def save_img(img_src):
    resp = requests.get(img_src, headers=headers)
    d = datetime.datetime.now()
    file_name = str(d.today()).split()[0] + '.jpg'
    # print(img_src)
    # print(file_name)    # 更改保存路径
    file_path = os.path.join('D:\pictures\Saved Pictures', file_name)
    # file_path = 'D:\pictures\Saved Pictures' + '/' + file_name

    with open(file_path, mode='wb') as f:
        f.write(resp.content)
    print(f'{file_name}下载完毕')


if __name__ == '__main__':
    img_src = get_src()
    save_img(img_src)
